package com.emagic.manage.modules.main.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.emagic.manage.LifeApplication;
import com.emagic.manage.R;
import com.emagic.manage.common.preference.UserSharedPreference;
import com.emagic.manage.common.ui.base.ToolBarActivity;
import com.emagic.manage.data.entities.response.RoomsResponse;
import com.emagic.manage.data.entities.response.UserResponse;
import com.emagic.manage.modules.loginmodule.activity.LoginActivity;
import com.emagic.manage.modules.main.presenter.OutOffAppPresenter;
import com.emagic.manage.modules.main.view.OutOffAppView;
import com.google.gson.Gson;
import com.xitaiinfo.library.commons.rx.Rx;

import java.util.HashMap;

import javax.inject.Inject;

import butterknife.ButterKnife;

/**
 * Created by xiatian on 2017/11/1.
 */

public class MainActivityNew extends ToolBarActivity implements OutOffAppView {


    ImageView mRefreshImg;
    ImageView mOutOff;
    ImageView mNamePhoto;
    TextView mUserName;
    TextView mTypeName;
    WebView mWebView;

    @Inject
    OutOffAppPresenter mOutOffAppPresenter;;

    private ProgressDialog mProgressDialog;

    private UserResponse mUser = new UserResponse();

    private RoomsResponse.RoomsEntity roomsEntity;
    private String TAG = MainActivityNew.class.getSimpleName();

    public static Intent getCallingIntent(Context context) {
        return new Intent(context, MainActivityNew.class);
    }

    private void initView() {
        getToolbar().setVisibility(View.GONE);
        mUserName.setText(mUser.getFirstname());
        if (mUser.getUserroleid().equals("0")) {
            mTypeName.setText("[老师]");
        } else if (mUser.getUserroleid().equals("1")) {
            mTypeName.setText("[助教]");
        } else if (mUser.getUserroleid().equals("2")) {
            mTypeName.setText("[学生]");
        }
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new AndroidBridge(), "JSWhitePadInterface"); //将那个实例化的函数类设置为”android"的js接口。
        //启用数据
        mWebView.getSettings().setDatabaseEnabled(true);
        //启用地理定位
        mWebView.getSettings().setGeolocationEnabled(true);
        //开启DomStorage缓存
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.getSettings().setDefaultTextEncodingName("utf_8");
        String url = "https://www.weiyiclass.com/static/pad_demo/calendar.html?userid=".concat(mUser.getUserid())
                .concat("&userroleid=").concat(mUser.getUserroleid()).concat("&clienttype=").concat("3");
        mWebView.loadUrl(url);
        Log.e(TAG, "initView:url: " + url);
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();// 接受所有网站的证书
            }

        });
        Rx.click(mRefreshImg, 1000, v -> {
            mWebView.loadUrl("javascript:refresh()");
        });
        Rx.click(mOutOff, 1000, v -> {
            mOutOffAppPresenter.outOff(mUser.getUserid(), mUser.getSessionid());
        });
    }

    private class AndroidBridge {

        @JavascriptInterface
        public void enterRoom(final String jsonStr) {
            Log.e(TAG, "enterRoom: " + jsonStr);
            System.out.println("jsonStrsend===========" + jsonStr);

            Gson gson = new Gson();
            HashMap message = new HashMap<>();
            message = gson.fromJson(jsonStr, message.getClass());

            String serial = message.containsKey("serial") ? message.get("serial").toString() : "";
            String roomname = message.containsKey("roomname") ? message.get("roomname").toString() : "";
            String chairmanpwd = message.containsKey("chairmanpwd") ? message.get("chairmanpwd").toString() : "";
            String confuserpwd = message.containsKey("confuserpwd") ? message.get("confuserpwd").toString() : "";
            String roomtype = message.containsKey("roomtype") ? message.get("roomtype").toString() : "";

            if (!TextUtils.isEmpty(serial) && !TextUtils.isEmpty(roomname) && !TextUtils.isEmpty(chairmanpwd)
                    && !TextUtils.isEmpty(confuserpwd) && !TextUtils.isEmpty(roomtype)) {
                roomsEntity = new RoomsResponse.RoomsEntity();
                roomsEntity.setSerial(serial);
                roomsEntity.setRoomname(roomname);
                roomsEntity.setChairmanpwd(chairmanpwd);
                roomsEntity.setConfuserpwd(confuserpwd);
                roomsEntity.setRoomtype(roomtype);
                if (LifeApplication.getInstance().getCurrentUser().getUserroleid().equals("0")) {
                    if ("0".equals(roomtype)) {
                        getNavigator().navigateToTRoomOneActivity(MainActivityNew.this,
                                serial, chairmanpwd, confuserpwd, roomname, 1002);
                    } else {
                        getNavigator().navigateToTRoomActivity(MainActivityNew.this,
                                serial, chairmanpwd, confuserpwd, roomname, 1002);
                    }
                } else {
                    getNavigator().navigateToRoomActivity(MainActivityNew.this,
                            serial, chairmanpwd, confuserpwd, roomname, roomtype, 1001);
                }
            }
        }


    }

    @Override
    protected void onCreate(@NonNull Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_new);
        ButterKnife.bind(this);
        mOutOffAppPresenter.attachView(this);
        findView();
        if (LifeApplication.getInstance().getCurrentUser() != null) {
            mUser = LifeApplication.getInstance().getCurrentUser();
            initView();
        }
    }

    private void findView() {
        mRefreshImg = (ImageView) findViewById(R.id.refresh_img);
        mOutOff = (ImageView) findViewById(R.id.out_off);
        mNamePhoto = (ImageView) findViewById(R.id.name_photo);
        mUserName = (TextView) findViewById(R.id.user_name);
        mTypeName = (TextView) findViewById(R.id.type_name);
        mWebView = (WebView) findViewById(R.id.web_view);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mOutOffAppPresenter.onDestroy();
        if (mWebView != null) {
            mWebView.removeAllViews();
            mWebView.destroy();
        }
    }

    @Override
    public void outOffSuccess() {
        UserSharedPreference preference = UserSharedPreference.getInstance(getContext());
        preference.clear();
        String phone = LifeApplication.getInstance().getCurrentUser().getAccount();
        LifeApplication.getInstance().release();
        Intent intentToLaunch = LoginActivity.getCallingIntent(getContext(), phone);
        intentToLaunch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intentToLaunch);
    }

    @Override
    public void showProgress() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("正在退出...");
            mProgressDialog.setCancelable(false);
            mProgressDialog.setCanceledOnTouchOutside(false);
        }

        mProgressDialog.show();
    }

    @Override
    public void hideProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && data != null) {
            getNavigator().navigateToRoomActivity(MainActivityNew.this,
                    roomsEntity.getSerial(), roomsEntity.getChairmanpwd(),
                    roomsEntity.getConfuserpwd(), roomsEntity.getRoomname(),
                    roomsEntity.getRoomtype(), 1001);
        } else {
            mWebView.loadUrl("javascript:refresh()");
        }
    }
}
